<template>
	<a-select
		allowClear
		:class="[
			'app-editor-container',
			'app-dropdown-list',
			`app-dropdown-list-${name}`,
		]"
		:value="curValue"
		:options="items"
		:mode="multiple ? 'multiple' : undefined"
		:disabled="disabled || readonly"
		:placeholder="placeholder"
		@change="onChange"
	>
	</a-select>
</template>
<script setup lang="ts">
import { onBeforeMount, Ref, ref } from 'vue';
import { dropdownListProps } from './dropdown-list';
import { IParam, IEvent, ICodeListItem } from '@/core';
import { typeOf } from '@/core';
import { handleEditorNavParams } from '@/hooks/use-editor';

interface EditorEmit {
	(name: 'component-action', value: IEvent<string>): void;
}
const props = defineProps(dropdownListProps);
const emit = defineEmits<EditorEmit>();
const { navContext, navViewParam } = handleEditorNavParams(props);
let curValue: Ref<any> = computed(() => {
	if (props.multiple) {
		return props.value ? props.value.split(props.valueSeparator) : [];
	} else {
		return props.value;
	}
});
let items: Ref<IParam[]> = ref([]);

const onChange = (select: any, option: any) => {
	const value =
		typeOf(select) == 'array' ? select.join(props.valueSeparator) : select;
	emit('component-action', {
		name: props.name as string,
		action: 'valueChange',
		data: value,
	});
};
onBeforeMount(() => {
	loadData();
});

const formatCodeList = (items: Array<any>) => {
	let matching = false;
	let result: Array<any> = [];
	try {
		items.forEach((item: any) => {
			const type = typeOf(item.value);
			if (type != props.valueType) {
				matching = true;
				if (type === 'number') {
					item.value = item.value.toString();
				} else {
					if (type == 'null') {
						props.valueType == 'number' ? (item.value = 0) : (item.value = '');
					} else if (item.value.indexOf('.') == -1) {
						item.value = parseInt(item.value);
					} else {
						item.value = parseFloat(item.value);
					}
				}
			}
			result.push(item);
		});
		if (matching) {
			console.warn(
				App.ts(
					'common.generic.codelistcast',
					'代码表值类型和属性类型不匹配，自动强制转换'
				)
			);
		}
		return result;
	} catch (error) {
		console.warn(
			App.ts(
				'common.generic.codelistwarn',
				'代码表值类型和属性类型不匹配，自动强制转换异常，请修正代码表值类型和属性类型匹配'
			)
		);
		return [];
	}
};

const loadData = async () => {
	if (props.codeListTag && props.codeListType) {
		await App.getAppCodeListHelper()
			.getCodeListItems(props.codeListTag, navContext, navViewParam)
			.then((codeListResult: any) => {
				if (codeListResult.ok) {
					const result = formatCodeList(codeListResult.data);
					result.forEach((item: ICodeListItem) => {
						items.value.push({ ...item, label: item.text });
					});
				}
			})
			.catch((error: any) => {
				console.warn(App.ts('common.generic.codenotexist', '代码表不存在'));
			});
	}
};
</script>
